package com.daxt.controller.infomanager;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.UserInfoUtil;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.result.*;
import com.daxt.mapper.archives.ArchivesDocFileMapper;
import com.daxt.mapper.archives.ArchivesStatisticsMapper;
import com.daxt.mapper.sys.DicMapper;
import com.daxt.mapper.use.UseBorrowRecordMapper;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.dic.*;
import com.daxt.model.dto.ArchivesStatisticsDto;
import com.daxt.model.dto.ArchivesStatisticsParamDto;
import com.daxt.model.dto.Classifys;
import com.daxt.model.service.archives.result.ArchivesStatisticsList;
import com.daxt.model.service.archives.vo.*;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.base.vo.Dic;
import com.daxt.model.service.use.vo.UseBorrowRecord;
import com.daxt.service.ArchivesService;
import com.daxt.service.UserService;
import com.daxt.utils.BaseUtil;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.sys.ArchivesFondsMapper;
import com.daxt.mapper.sys.ArchivesTypeMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "档案统计")
@RestController
@RequestMapping("/infoManage")
public class StatisticsController {

    @Autowired
    private ArchivesFondsMapper archivesFondsMapper;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private ArchivesStatisticsMapper archivesStatisticsMapper;
    @Autowired
    private UseBorrowRecordMapper useBorrowRecordMapper;
    @Autowired
    private DicMapper dicMapper;
    @Autowired
    private ArchivesDocFileMapper archivesDocFileMapper;


    @ApiOperation(value = "档案统计", notes = "")
    @GetMapping("/statistics/all")
    public Result<Map<String, Object>> all(HttpServletRequest request) {

        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        if (loginInfo == null) {
            return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
        }
        //获取用户数据权限
        Classifys c = userService.buildUserClassifys(loginInfo);
        List<Long> afIds = c.getFonds();//全宗ids
        List<Long> categoryIds = c.getCategoryIds();//门类ids
        List<Long> classIds = c.getClassIds();//类目ids
        List<String> fieldYearIds = c.getFieldYearIds();//字段年度ids


        Map<String, Object> map = new HashMap<String, Object>();
        QueryWrapper<ArchivesFonds> qwFonds = new QueryWrapper<ArchivesFonds>();
        if (BaseUtil.listIsNotNullElement(afIds)) qwFonds.in("id", afIds);
        Integer fondsCount = archivesFondsMapper.selectCount(qwFonds);
        map.put("fondsCount", fondsCount != null ? fondsCount : 0);
        QueryWrapper<ArchivesType> qwType = new QueryWrapper<ArchivesType>();
        if (BaseUtil.listIsNotNullElement(categoryIds)) qwType.in("id", categoryIds);
        Integer typeCount = archivesTypeMapper.selectCount(qwType);
        map.put("typeCount", typeCount != null ? typeCount : 0);
        QueryWrapper<ArchivesDoc> queryWrapperDoc = new QueryWrapper<ArchivesDoc>();
        queryWrapperDoc.eq("fileType", "dossier");
        queryWrapperDoc.eq("isDelete", "0");
        queryWrapperDoc.eq("state", "2");

        //增加数据权限条件
        queryWrapperDoc = archivesService.builQueryWrapper(queryWrapperDoc, c);

        Integer dossierCount = archivesDocMapper.selectCount(queryWrapperDoc);
        map.put("dossierCount", dossierCount != null ? dossierCount : 0);
        QueryWrapper<ArchivesDoc> queryWrapperDoc1 = new QueryWrapper<ArchivesDoc>();
        queryWrapperDoc1.eq("fileType", "doc");
        queryWrapperDoc1.eq("isDelete", "0");
        queryWrapperDoc1.eq("state", "2");

        //增加数据权限条件
        queryWrapperDoc1 = archivesService.builQueryWrapper(queryWrapperDoc1, c);

        Integer docCount = archivesDocMapper.selectCount(queryWrapperDoc1);
        map.put("docCount", docCount != null ? docCount : 0);
        QueryWrapper<ArchivesDoc> queryWrapperDoc2 = new QueryWrapper<ArchivesDoc>();
        queryWrapperDoc2.eq("fileType", "doc");
        queryWrapperDoc2.eq("isDelete", "0");
        queryWrapperDoc2.eq("state", "0");
        //增加数据权限条件
        queryWrapperDoc2 = archivesService.builQueryWrapper(queryWrapperDoc2, c);

        Integer zlCount = archivesDocMapper.selectCount(queryWrapperDoc2);
        map.put("zlCount", zlCount != null ? zlCount : 0);
        QueryWrapper<ArchivesDoc> queryWrapperDoc3 = new QueryWrapper<ArchivesDoc>();
        queryWrapperDoc3.eq("fileType", "dossier");
        queryWrapperDoc3.eq("isDelete", "0");
        queryWrapperDoc3.eq("state", "3");
        //增加数据权限条件
        queryWrapperDoc3 = archivesService.builQueryWrapper(queryWrapperDoc3, c);

        Integer jdjuanCount = archivesDocMapper.selectCount(queryWrapperDoc3);
        map.put("jdjuanCount", jdjuanCount != null ? jdjuanCount : 0);
        QueryWrapper<ArchivesDoc> queryWrapperDoc4 = new QueryWrapper<ArchivesDoc>();
        queryWrapperDoc4.eq("fileType", "doc");
        queryWrapperDoc4.eq("isDelete", "0");
        queryWrapperDoc4.eq("state", "3");
        //增加数据权限条件
        queryWrapperDoc4 = archivesService.builQueryWrapper(queryWrapperDoc4, c);

        Integer jdjianCount = archivesDocMapper.selectCount(queryWrapperDoc4);
        map.put("jdjianCount", jdjianCount != null ? jdjianCount : 0);
        QueryWrapper<ArchivesDoc> queryWrapperDoc5 = new QueryWrapper<ArchivesDoc>();
        queryWrapperDoc5.eq("fileType", "dossier");
        queryWrapperDoc5.eq("openState", "2");
        queryWrapperDoc5.in("state", new String[]{"2", "3"});
        //增加数据权限条件
        queryWrapperDoc5 = archivesService.builQueryWrapper(queryWrapperDoc5, c);

        Integer ojuanCount = archivesDocMapper.selectCount(queryWrapperDoc5);
        map.put("ojuanCount", ojuanCount != null ? ojuanCount : 0);
        QueryWrapper<ArchivesDoc> queryWrapperDoc6 = new QueryWrapper<ArchivesDoc>();
        queryWrapperDoc6.eq("fileType", "doc");
        queryWrapperDoc6.eq("openState", "2");
        queryWrapperDoc6.eq("isDelete", "0");
        queryWrapperDoc6.in("state", new String[]{"2", "3"});
        //增加数据权限条件
        queryWrapperDoc6 = archivesService.builQueryWrapper(queryWrapperDoc6, c);
        Integer ojianCount = archivesDocMapper.selectCount(queryWrapperDoc6);
        map.put("ojianCount", ojianCount != null ? ojianCount : 0);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", map);
    }


    @ApiOperation(value = "年度门类统计", notes = "")
    @GetMapping("/statistics/{fondsId}")
    public Result<Map<String, Object>> yearStatisticsType(@PathVariable("fondsId") String fondsId, @ApiParam("") @RequestParam(value = "year", required = false) String year) {
        String[] split = null;
        if (!StringUtils.isEmpty(year)) {
            if (!year.contains("~")) {
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请选择开始日期和结束日期", null);
            }
            split = year.split("~");
        }
        QueryWrapper<ArchivesType> queryWrapperType = new QueryWrapper<ArchivesType>();
        queryWrapperType.eq("fondsId", fondsId);
        List<ArchivesType> typeList = archivesTypeMapper.selectList(queryWrapperType);
        List<String> typeKey = new ArrayList<String>();
        List<Map<String, Object>> typeValue = new ArrayList<>();
        for (ArchivesType archivesType : typeList) {
            String typeNum = archivesType.getTypeNum();
            QueryWrapper<ArchivesDoc> queryWrapperDoc = new QueryWrapper<ArchivesDoc>();
            queryWrapperDoc.eq("fondsId", fondsId);
            queryWrapperDoc.eq("typeNum", typeNum);
            if (null != split) {
                queryWrapperDoc.between("archivalYear", split[0], split[1]);
            }
            queryWrapperDoc.eq("isDelete", "0");
            queryWrapperDoc.in("state", new String[]{"2", "3"});
            Integer selectCount = archivesDocMapper.selectCount(queryWrapperDoc);
            Map<String, Object> tempMap = new HashMap<String, Object>();
            tempMap.put("name", archivesType.getTypeName());
            tempMap.put("value", selectCount == null ? 0 : selectCount);
            typeValue.add(tempMap);
            typeKey.add(archivesType.getTypeName());
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("typeKey", typeKey);
        result.put("typeValue", typeValue);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", result);
    }


//    @ApiOperation(value = "年度月份统计", notes = "")
//    @GetMapping("/statistics/mouth/{fondsId}/{year}")
//    public Result<Map<String, List>> yearStatistics(@PathVariable("fondsId") String fondsId, @PathVariable("year") String year) {
//        if (!year.contains("~")) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请选择开始日期和结束日期", null);
//        }
//        String[] split = year.split("~");
//        List<Map<String, Integer>> string = new ArrayList<Map<String, Integer>>();
//        for (int i = 1; i < 13; i++) {
//            Map<String, Integer> map = new HashMap<String, Integer>();
//            map.put(i + "", 0);
//            string.add(map);
//        }
//        QueryWrapper<ArchivesType> queryWrapperType = new QueryWrapper<ArchivesType>();
//        queryWrapperType.eq("fondsId", fondsId);
//        List<ArchivesType> typeList = archivesTypeMapper.selectList(queryWrapperType);
//
//        for (ArchivesType archivesType : typeList) {
//            String typeNum = archivesType.getTypeNum();
//            QueryWrapper<ArchivesDoc> queryWrapperDoc = new QueryWrapper<ArchivesDoc>();
//            queryWrapperDoc.eq("fondsId", fondsId);
//            queryWrapperDoc.eq("typeNum", typeNum);
//            queryWrapperDoc.eq("isDelete", "0");
//            queryWrapperDoc.in("state", new String[]{"2", "3"});
//            queryWrapperDoc.between("archivalYear", split[0], split[1]);
//            List<ArchivesDoc> docList = archivesDocMapper.selectList(queryWrapperDoc);
//            for (ArchivesDoc doc : docList) {
//                int mouthCount = 0;
//                try {
//                    int nowTimeMouth = LocalDateTimeUtil.getNowTimeMouth(doc.getEndTime());
//                    mouthCount = nowTimeMouth;
//                    Map<String, Integer> map = string.get(mouthCount - 1);
//                    Integer count = map.get(mouthCount + "");
//                    map.put(mouthCount + "", count + 1);
//                    string.set(mouthCount - 1, map);
//                } catch (Exception e) {
//                }
//            }
//
//        }
//        List<String> monthList = new ArrayList<String>();
//        List<Integer> monthValueList = new ArrayList<Integer>();
//        int index = 0;
//        for (int i = 0; i < 12; i++) {
//            Map<String, Integer> map = string.get(i);
//            monthList.add((i + 1) + "月");
//            Integer integer = map.get((i + 1) + "");
//            if (integer != null && integer > 0) {
//                index++;
//            }
//            monthValueList.add(integer);
//        }
//        Map<String, List> result = new HashMap<String, List>();
//        result.put("monthList", monthList);
//        result.put("monthValueList", index == 0 ? new ArrayList<Integer>() : monthValueList);
//        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", result);
//    }

    @ApiOperation(value = "年度门类件卷统计", notes = "")
    @GetMapping("/statistics/type/{fondsId}")
    public Result<Map<String, Object>> yearStatisticsTypeCount(@PathVariable("fondsId") String fondsId, @ApiParam("") @RequestParam(value = "year", required = false) String year
            , @ApiParam("") @RequestParam(value = "typeId", required = false) String typeId) {

        String[] split = null;
        if (!StringUtils.isEmpty(year)) {
            if (!year.contains("~")) {
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请选择开始日期和结束日期", null);
            }
            split = year.split("~");
        }
        QueryWrapper<ArchivesType> queryWrapperType = new QueryWrapper<ArchivesType>();
        queryWrapperType.eq("fondsId", fondsId);
        List<ArchivesType> typeList = archivesTypeMapper.selectList(queryWrapperType);
        List<String> title = new ArrayList<String>();
        List<Integer> docValue = new ArrayList<>();
        List<Integer> dossierValue = new ArrayList<>();
        for (ArchivesType archivesType : typeList) {
            QueryWrapper<ArchivesDoc> queryWrapperDossier = new QueryWrapper<ArchivesDoc>();
            queryWrapperDossier.eq("fondsId", fondsId);
            if (StringUtils.isNotEmpty(typeId)) queryWrapperDossier.eq("typeId", typeId);
            if (null != split) queryWrapperDossier.between("archivalYear", split[0], split[1]);
            queryWrapperDossier.eq("fileType", "dossier");
            queryWrapperDossier.eq("isDelete", "0");
            queryWrapperDossier.in("state", new String[]{"2", "3"});
            Integer dossierCount = archivesDocMapper.selectCount(queryWrapperDossier);
            QueryWrapper<ArchivesDoc> queryWrapperDoc = new QueryWrapper<ArchivesDoc>();
            queryWrapperDoc.eq("fondsId", fondsId);
            if (StringUtils.isNotEmpty(typeId)) queryWrapperDoc.eq("typeId", typeId);
            if (null != split) queryWrapperDoc.between("archivalYear", split[0], split[1]);
            queryWrapperDoc.eq("fileType", "doc");
            queryWrapperDoc.eq("isDelete", "0");
            queryWrapperDoc.in("state", new String[]{"2", "3"});
            Integer docCount = archivesDocMapper.selectCount(queryWrapperDoc);
            title.add(archivesType.getTypeName());
            docValue.add(docCount == null ? 0 : docCount);
            dossierValue.add(dossierCount == null ? 0 : dossierCount);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("title", title);
        result.put("docValue", docValue);
        result.put("dossierValue", dossierValue);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", result);
    }


//    @ApiOperation(value = "档案统计", notes = "")
//    @GetMapping("/statistics/fondsId/{fondsId}")
//    public Result<Map<String, Object>> fonds(@PathVariable("fondsId") String id, @ApiParam("") @RequestParam(value = "year", required = false) String year
//            , @ApiParam("") @RequestParam(value = "typeNumId", required = false) String typeNumId) {
//
//        String[] split = null;
//        if (!StringUtils.isEmpty(year)) {
//            if (!StringUtils.isEmpty(year) && !year.contains("~")) {
//                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请选择开始日期和结束日期", null);
//            }
//            split = year.split("~");
//        }
//
//        String typeNum = null;
//        if (StringUtils.isNotEmpty(typeNumId)) {
//            ArchivesType archivesType = archivesTypeMapper.selectById(typeNumId);
//            if (null != archivesType) typeNum = archivesType.getTypeNum();
//
//        }
//
//
//        Map<String, Object> map = new HashMap<String, Object>();
//        QueryWrapper<ArchivesType> queryWrapperType = new QueryWrapper<ArchivesType>();
//        queryWrapperType.eq("fondsId", id);
//        if (StringUtils.isNotEmpty(typeNum)) queryWrapperType.eq("typeNum", typeNum);
//        Integer typeCount = archivesTypeMapper.selectCount(queryWrapperType);
//        map.put("typeCount", typeCount != null ? typeCount : 0);
//        QueryWrapper<ArchivesDoc> queryWrapperDoc = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc.eq("fileType", "dossier");
//        queryWrapperDoc.eq("fondsId", id);
//        queryWrapperDoc.eq("isDelete", "0");
//        queryWrapperDoc.eq("state", "2");
//        if (null != split) queryWrapperDoc.between("archivalYear", split[0], split[1]);
//        if (StringUtils.isNotEmpty(typeNum)) queryWrapperDoc.eq("typeNum", typeNum);
//        Integer dossierCount = archivesDocMapper.selectCount(queryWrapperDoc);
//        map.put("dossierCount", dossierCount != null ? dossierCount : 0);
//        QueryWrapper<ArchivesDoc> queryWrapperDoc1 = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc1.eq("fileType", "doc");
//        queryWrapperDoc1.eq("fondsId", id);
//        queryWrapperDoc1.eq("isDelete", "0");
//        queryWrapperDoc1.eq("state", "2");
//        if (StringUtils.isNotEmpty(typeNum)) queryWrapperDoc1.eq("typeNum", typeNum);
//        if (null != split) queryWrapperDoc1.between("archivalYear", split[0], split[1]);
//        Integer docCount = archivesDocMapper.selectCount(queryWrapperDoc1);
//        map.put("docCount", docCount != null ? docCount : 0);
//        QueryWrapper<ArchivesDoc> queryWrapperDoc2 = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc2.eq("fileType", "doc");
//        queryWrapperDoc2.eq("fondsId", id);
//        queryWrapperDoc2.eq("isDelete", "0");
//        queryWrapperDoc2.eq("state", "0");
//        if (StringUtils.isNotEmpty(typeNum)) queryWrapperDoc2.eq("typeNum", typeNum);
//        if (null != split) queryWrapperDoc2.between("archivalYear", split[0], split[1]);
//        Integer zlCount = archivesDocMapper.selectCount(queryWrapperDoc2);
//        map.put("zlCount", zlCount != null ? zlCount : 0);
//        QueryWrapper<ArchivesDoc> queryWrapperDoc3 = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc3.eq("fileType", "dossier");
//        queryWrapperDoc3.eq("fondsId", id);
//        queryWrapperDoc3.eq("isDelete", "0");
//        queryWrapperDoc3.eq("state", "3");
//        if (StringUtils.isNotEmpty(typeNum)) queryWrapperDoc3.eq("typeNum", typeNum);
//        if (null != split) queryWrapperDoc3.between("archivalYear", split[0], split[1]);
//        Integer jdjuanCount = archivesDocMapper.selectCount(queryWrapperDoc3);
//        map.put("jdjuanCount", jdjuanCount != null ? jdjuanCount : 0);
//        QueryWrapper<ArchivesDoc> queryWrapperDoc4 = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc4.eq("fileType", "doc");
//        queryWrapperDoc4.eq("fondsId", id);
//        queryWrapperDoc4.eq("isDelete", "0");
//        queryWrapperDoc4.eq("state", "3");
//        if (StringUtils.isNotEmpty(typeNum)) queryWrapperDoc4.eq("typeNum", typeNum);
//        if (null != split) queryWrapperDoc4.between("archivalYear", split[0], split[1]);
//        Integer jdjianCount = archivesDocMapper.selectCount(queryWrapperDoc4);
//        map.put("jdjianCount", jdjianCount != null ? jdjianCount : 0);
//        QueryWrapper<ArchivesDoc> queryWrapperDoc5 = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc5.eq("fileType", "dossier");
//        queryWrapperDoc5.eq("openState", "2");
//        queryWrapperDoc5.eq("fondsId", id);
//        queryWrapperDoc5.eq("isDelete", "0");
//        queryWrapperDoc5.eq("openState", "2");
//        queryWrapperDoc5.eq("state", "2");
//        if (null != split) queryWrapperDoc5.between("archivalYear", split[0], split[1]);
//        if (StringUtils.isNotEmpty(typeNum)) queryWrapperDoc5.eq("typeNum", typeNum);
//        Integer ojuanCount = archivesDocMapper.selectCount(queryWrapperDoc5);
//        map.put("ojuanCount", ojuanCount != null ? ojuanCount : 0);
//        QueryWrapper<ArchivesDoc> queryWrapperDoc6 = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc6.eq("fileType", "doc");
//        queryWrapperDoc6.eq("openState", "2");
//        queryWrapperDoc6.eq("fondsId", id);
//        queryWrapperDoc6.eq("isDelete", "0");
//        queryWrapperDoc6.eq("openState", "2");
//        queryWrapperDoc6.eq("state", "2");
//        if (null != split) queryWrapperDoc6.between("archivalYear", split[0], split[1]);
//        if (StringUtils.isNotEmpty(typeNum)) queryWrapperDoc6.eq("typeNum", typeNum);
//        Integer ojianCount = archivesDocMapper.selectCount(queryWrapperDoc6);
//        map.put("ojianCount", ojianCount != null ? ojianCount : 0);
//        map.put("index", 1);
//        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", map);
//    }


    @ApiOperation(value = "档案统计（检索）", notes = "")
    @GetMapping("/statistics/searching")
    public Result<PageInfo<ArchivesStatisticsList>> look(
            @ApiParam("") @RequestParam(value = "year", required = false) String year,
            @ApiParam("排序（1卷降序、2件降序，默认1）") @RequestParam(value = "sort", required = false) String sort,
            @ApiParam("标识（2全宗统计，3门类统计）") @RequestParam(value = "mark", required = true) String mark,
            @ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize
    ) {

//        if (StringUtils.isEmpty(year)) {
//            LocalDate ld = LocalDate.now();
//            year = String.valueOf(ld.getYear());
//        }

        Page<ArchivesStatistics> page = new Page<ArchivesStatistics>(pageNum == null ? 0 : pageNum,
                pageSize == null ? 10 : pageSize);
        Map<String, Object> param = new HashMap<String, Object>();

        String sortStr = " dossierNum desc";
        if (StringUtils.isNotEmpty(sort) && sort.equals("2")) {
            sortStr = " docNum desc";
        }

        param.put("year", year);
        param.put("sortStr", sortStr);

        IPage<ArchivesStatisticsList> pageList = null;
        if (mark.equals("2")) {
            pageList = archivesStatisticsMapper.countFonds(page, param);
        } else if (mark.equals("3")) {
            pageList = archivesStatisticsMapper.countType(page, param);

        } else {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "标识输入错误，请正确填写！", null);
        }

        PageInfo<ArchivesStatisticsList> data = PageUtil.data(pageList.getPages(), pageList.getCurrent(), pageList.getTotal(),
                pageList.getRecords());


        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", data);
    }


    @ApiOperation(value = "《总》档案统计（检索）", notes = "")
    @GetMapping("/statistics/totalSearching")
    public Result<ArchivesStatisticsList> totalSearching(@ApiParam("") @RequestParam(value = "year", required = false) String year) {

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("year", year);

        ArchivesStatisticsList aslBean = archivesStatisticsMapper.countAll(param);
        aslBean.setArchivesName(RedisUtil.getSysConfig(SystemConfigType.ARCHIVES_NAME));
        aslBean.setArchivesCode(RedisUtil.getSysConfig(SystemConfigType.ARCHIVES_CODE));


        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", aslBean);
    }


    @ApiOperation(value = "增加档案统计", notes = "")
    @PostMapping("/statistics/addCount")
    public Result<String> addCount(
            @ApiParam("年份") @RequestParam(value = "year", required = false) String year,
            @ApiParam("全宗号") @RequestParam(value = "fondsId", required = true) String fondsId,
            @ApiParam("门类号") @RequestParam(value = "type", required = true) String type,
            @ApiParam("模式（1件、0卷）") @RequestParam(value = "pattern", required = true) String pattern
    ) {
        if (StringUtils.isEmpty(fondsId)) return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "全宗ID为空", null);
        if (StringUtils.isEmpty(type)) return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "门类号为空", null);
        if (StringUtils.isNotEmpty(pattern) &&
                !(pattern.equals(DicDocPattern.PATTERN_1.getKey()) || pattern.equals(DicDocPattern.PATTERN_0.getKey())))
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "模式输入有误", null);

        if (StringUtils.isEmpty(year)) {
            LocalDate ld = LocalDate.now();
            year = String.valueOf(ld.getYear());
        }
        archivesService.addCount(fondsId, type, pattern, year);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "增加统计", null);

    }


    @ApiOperation(value = "(首页)档案基本信息统计", notes = "")
    @GetMapping("/statistics")
    @LoginAuth()
    public Result<ArchivesStatisticsDto> count(@LoginUser UserInfo loginUser) {

        String userName=loginUser.getUsername();
        String role=loginUser.getRole();
        String fondsId=loginUser.getFondsId();

        ArchivesStatisticsDto dto = new ArchivesStatisticsDto();

        //==========总件数

        //卷数
        QueryWrapper<ArchivesDoc> dossierQw = new QueryWrapper<>();
        //if(!"admin".equals(userName) && !"超级管理员".equals(role)){
            dossierQw.eq(StringUtils.isNotEmpty(fondsId),"fondsId",fondsId);
        //}
        dossierQw.eq("state", DicDocState.archive.getKey());
        dossierQw.eq("fileType", DicDocFileType.DOSSIER.getKey());
        dossierQw.eq("isDelete", BaseConstants.DELETE_NORMAL);
        int dossierNum = archivesDocMapper.selectCount(dossierQw);

        //件数
        QueryWrapper<ArchivesDoc> docQw = new QueryWrapper<>();
        if(!"admin".equals(userName) && !"超级管理员".equals(role)){
            docQw.eq(StringUtils.isNotEmpty(fondsId),"fondsId",fondsId);
        }
        docQw.eq("dossierId", "0");
        docQw.eq("state", DicDocState.archive.getKey());
        docQw.eq("fileType", DicDocFileType.DOC.getKey());
        docQw.eq("isDelete", BaseConstants.DELETE_NORMAL);
        int docNum = archivesDocMapper.selectCount(docQw);
        dto.setDocCount(dossierNum + docNum);


        //============借阅次数
        QueryWrapper<UseBorrowRecord> ubrWrapper = new QueryWrapper<>();
        if(!"admin".equals(userName) && !"超级管理员".equals(role)){
            ubrWrapper.eq(StringUtils.isNotEmpty(fondsId),"fondsId",fondsId);
        }
        ubrWrapper.and(Wrapper -> Wrapper.eq("state", "2").or().eq("state", "3"));
        dto.setBorrowCount(useBorrowRecordMapper.selectCount(ubrWrapper));
        if (null == dto.getBorrowCount()) dto.setBorrowCount(0);

        //待鉴定
        QueryWrapper<ArchivesDoc> jd = new QueryWrapper<>();
        if(!"admin".equals(userName) && !"超级管理员".equals(role)){
            jd.eq(StringUtils.isNotEmpty(fondsId),"fondsId",fondsId);
        }
        jd.eq("state", DicDocState.authenticate.getKey());
        jd.eq("isDelete", BaseConstants.DELETE_NORMAL);
        jd.and(Wrapper -> Wrapper.eq("dossierId", "0").or().isNull("dossierId"));
        dto.setToIdentifyCount(archivesDocMapper.selectCount(jd));
        if (null == dto.getToIdentifyCount()) dto.setToIdentifyCount(0);

        //待归档  审批状态
        QueryWrapper<ArchivesDoc> dgd = new QueryWrapper<>();
        if(!"admin".equals(userName) && !"超级管理员".equals(role)){
            dgd.eq(StringUtils.isNotEmpty(fondsId),"fondsId",fondsId);
        }
        dgd.eq("state", DicDocState.approval.getKey());
        dgd.eq("isDelete", BaseConstants.DELETE_NORMAL);
        dgd.and(Wrapper -> Wrapper.eq("dossierId", "0").or().isNull("dossierId"));
        dto.setToArchiveCount(archivesDocMapper.selectCount(dgd));
        if (null == dto.getToArchiveCount()) dto.setToArchiveCount(0);

        //待借阅   借阅审批状态
        QueryWrapper<UseBorrowRecord> djy = new QueryWrapper<>();
        if(!"admin".equals(userName) && !"超级管理员".equals(role)){
            djy.eq(StringUtils.isNotEmpty(fondsId),"fondsId",fondsId);
        }
        djy.eq("state", "0");
        dto.setToBorrowCount(useBorrowRecordMapper.selectCount(djy));
        if (null == dto.getToBorrowCount()) dto.setToBorrowCount(0);

        return ResultUtil.success(dto);


    }

    @ApiOperation(value = "(首页)档案保管期限统计", notes = "")
    @GetMapping("/statistics/storagePeriod")
    @LoginAuth()
    public Result<Map<String, Object>> storagePeriodCount(@LoginUser UserInfo loginUser) {
        String userName=loginUser.getUsername();
        String role=loginUser.getRole();
        String fondsId=loginUser.getFondsId();

        Map<String, Object> map = new HashMap<String, Object>();

        QueryWrapper<ArchivesDoc> qw = new QueryWrapper<>();
        //if(!"admin".equals(userName) && !"超级管理员".equals(role)){
            qw.eq(StringUtils.isNotEmpty(fondsId),"fondsId",fondsId);
        //}
        qw.eq("state", DicDocState.archive.getKey());
        qw.eq("isDelete", BaseConstants.DELETE_NORMAL);
        qw.and(Wrapper -> Wrapper.eq("dossierId", "0").or().isNull("dossierId"));
        List<ArchivesDoc> list = archivesDocMapper.selectList(qw);

        QueryWrapper<Dic> queryWrapper = new QueryWrapper<Dic>();
        queryWrapper.eq("dicType", "storagePeriod");
        queryWrapper.orderByAsc("sort");
        List<Dic> dicList = dicMapper.selectList(queryWrapper);

        for (Dic dic : dicList) {
            long count = list.stream().filter(ArchivesDoc -> StringUtils.isNotEmpty(ArchivesDoc.getStoragePeriod()) && ArchivesDoc.getStoragePeriod().equals(dic.getDicCode())).count();
            map.put(dic.getDicValue(), count);
        }

        return ResultUtil.success(map);

    }


    @ApiOperation(value = "(首页)档案门类统计", notes = "")
    @GetMapping("/statistics/type")
    @LoginAuth()
    public Result<Map> type(@LoginUser UserInfo loginUser) {

        String userName=loginUser.getUsername();
        String role=loginUser.getRole();
        String fondsId=loginUser.getFondsId();

        Map map = new LinkedHashMap();

        //改成首页统计的时候，根据全宗统计，超级管理员也是根据全宗统计
        QueryWrapper<ArchivesType> typeQw = new QueryWrapper<>();
        //if(!"admin".equals(userName) && !"超级管理员".equals(role)){
            typeQw.eq(StringUtils.isNotEmpty(fondsId),"fondsId",fondsId);
        //}
        //typeQw.groupBy("typeNum");
        typeQw.orderByAsc("sort");
        List<ArchivesType> typeList = archivesTypeMapper.selectList(typeQw);

        for (ArchivesType at : typeList) {
            QueryWrapper<ArchivesDoc> qw = new QueryWrapper<>();
            qw.eq("state", DicDocState.archive.getKey());
            qw.eq("isDelete", BaseConstants.DELETE_NORMAL);
            if (at.getModel().equals(DicDocPattern.PATTERN_1)) {
                qw.eq("fileType", DicDocFileType.DOSSIER);
            }
            if (at.getModel().equals(DicDocPattern.PATTERN_0)) {
                qw.eq("fileType", DicDocFileType.DOC);
            }
            qw.eq("typeId", at.getId());
            int i = archivesDocMapper.selectCount(qw);
            map.put(at.getTypeName(), i);
        }


        return ResultUtil.success(map);


    }


    @ApiOperation(value = "档案统计（全）", notes = "")
    @PostMapping("/statistics/all")
    @LoginAuth()
    public Result<ArchivesStatisticsDto> all(@ApiIgnore @LoginUser UserInfo loginUser, @RequestBody ArchivesStatisticsParamDto paramDto) {
        ArchivesStatisticsDto dto = new ArchivesStatisticsDto();

        if(!"admin".equals(loginUser.getUsername()) && !"超级管理员".equals(loginUser.getRole())){
            if(StringUtils.isNotEmpty(loginUser.getFondsId())){
                paramDto.setFondsId(loginUser.getFondsId());
            }
        }else{
            if (StringUtils.isEmpty(paramDto.getFondsId())){
                if(StringUtils.isNotEmpty(loginUser.getFondsId())){
                    paramDto.setFondsId(loginUser.getFondsId());
                }
            }

        }

        paramDto.setIsDelete(BaseConstants.DELETE_NORMAL);

        String[] yearSplit = null;
        if (!StringUtils.isEmpty(paramDto.getYear())) {
            if (!StringUtils.isEmpty(paramDto.getYear()) && !paramDto.getYear().contains("~")) {
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请选择开始日期和结束日期", null);
            }
            yearSplit = paramDto.getYear().split("~");
            paramDto.setYearStart(yearSplit[0]);
            paramDto.setYearEnd(yearSplit[1]);
        }

        String typeNum = null;
        if (StringUtils.isNotEmpty(paramDto.getTypeId())) {
            ArchivesType archivesType = archivesTypeMapper.selectById(paramDto.getTypeId());
            if (null != archivesType) {
                typeNum = archivesType.getTypeNum();
                paramDto.setTypeNum(typeNum);
            }

        }

        String fondsId = paramDto.getFondsId();
        String typeId = paramDto.getTypeId();


        //=========全宗数
        dto.setFonds(archivesService.statisticsFonds(fondsId));
        //=========门类数
        dto.setTypes(archivesService.statisticsType(fondsId, typeId));
        //=========卷数
        paramDto.setFileType("dossier");
        paramDto.setState("2");
        dto.setDossierCount(archivesService.statisticsArchives(paramDto));
        //=========件数
        paramDto.setFileType("doc");
        //paramDto.setState("2");
        //=========待整理件数
        dto.setDocCount(archivesService.statisticsArchives(paramDto));
        paramDto.setFileType("doc");
        paramDto.setState("0");
        dto.setToNeatenCount(archivesService.statisticsArchives(paramDto));
        //=========待鉴定卷数
        paramDto.setFileType("dossier");
        paramDto.setState("3");
        dto.setToIdentifyCount(archivesService.statisticsArchives(paramDto));
        //=========鉴定件数
        paramDto.setFileType("doc");
        paramDto.setState("3");
        dto.setIdentifyCount(archivesService.statisticsArchives(paramDto));

        //=========附件数
        Map<String, Object> filesParam = new HashMap();
        if (StringUtils.isNotEmpty(fondsId)) filesParam.put("fondsId", fondsId);
        if (StringUtils.isNotEmpty(typeId)) filesParam.put("typeId", typeId);
        if (StringUtils.isNotEmpty(paramDto.getYearStart()) && StringUtils.isNotEmpty(paramDto.getYearEnd())) {
            filesParam.put("yearStart", paramDto.getYearStart());
            filesParam.put("yearEnd", paramDto.getYearEnd());
        }
        if (StringUtils.isNotEmpty(paramDto.getFilingStartDate()) && StringUtils.isNotEmpty(paramDto.getFilingEndDate())) {
            filesParam.put("filingStartDate", paramDto.getFilingStartDate());
            filesParam.put("filingEndDate", paramDto.getFilingEndDate());
        } else if (StringUtils.isNotEmpty(paramDto.getFilingStartDate())) {
            filesParam.put("filingStartDate", paramDto.getFilingStartDate());
        }

        filesParam.put("state", DicDocState.archive.getKey());
        filesParam.put("isDelete", BaseConstants.DELETE_NORMAL);
        List<ArchivesDocFile> fileList = archivesDocMapper.queryFilesSize(filesParam);
//        Integer fileCount = Math.toIntExact(archivesDocMapper.countFiles(filesParam));
        dto.setFileCount(fileList.size());

        dto.setFileUnit("GB");

        double sum = fileList.stream().mapToDouble(ArchivesDocFile -> StringUtils.isNotEmpty(ArchivesDocFile.getFileSize()) ? Double.parseDouble(ArchivesDocFile.getFileSize()) : 0d).sum();
//        double sum = fileList.stream().mapToDouble(ArchivesDocFile -> Double.parseDouble(ArchivesDocFile.getFileSize())).sum();
        DecimalFormat a = new DecimalFormat("###0.0#");

        String totalByte = a.format(sum);
        System.err.println("文件总大小：" + totalByte);
        BigDecimal bg111 = new BigDecimal(totalByte);
        BigDecimal bg222 = BigDecimal.valueOf(1073741824d);//1024/1024/1024
        BigDecimal divide = bg111.divide(bg222, 2, BigDecimal.ROUND_DOWN);
        dto.setFileSize(divide.toString());

        //========门类统计   查询很慢要优化
        paramDto.setFileType(null);
        paramDto.setState(DicDocState.archive.getKey());
        paramDto.setIsDelete(BaseConstants.DELETE_NORMAL);
        //dto.setTypeMap(archivesService.gainStatisticsType(paramDto));

        if (!RedisUtil.isAppoint(VersionsMarkType.VERSIONS_1)) {
            dto.setTypeList(archivesService.gainStatisticsType(paramDto));
        }


        //== 保管期限
        QueryWrapper<ArchivesDoc> qw = archivesService.buildStatisticsQueryWrapper(null, paramDto);
        qw.select("id,storagePeriod,dossierId,fileType");
        qw.and(Wrapper -> Wrapper.eq("dossierId", "0").or().isNull("dossierId"));
        List<ArchivesDoc> list = archivesDocMapper.selectList(qw);


        QueryWrapper<Dic> queryWrapper = new QueryWrapper<Dic>();
        queryWrapper.eq("dicType", "storagePeriod");
        queryWrapper.orderByAsc("sort");
        List<Dic> dicList = dicMapper.selectList(queryWrapper);

        Map storagePeriodMap = new HashMap();
//        for (Dic dic : dicList) {
//            long count = list.stream().filter(ArchivesDoc -> StringUtils.isNotEmpty(ArchivesDoc.getStoragePeriod()) && ArchivesDoc.getStoragePeriod().equals(dic.getDicCode())).count();
//            storagePeriodMap.put(dic.getDicValue(),count);
//        }

        for (Dic dic : dicList) {
            long dossierNum = 0;
            long docNum = 0;
            dossierNum = list.stream().filter(ArchivesDoc ->
                    StringUtils.isNotEmpty(ArchivesDoc.getStoragePeriod()) && ArchivesDoc.getStoragePeriod().equals(dic.getDicCode()) && ArchivesDoc.getFileType().equals(DicDocFileType.DOSSIER.getKey())
            ).count();
            docNum = list.stream().filter(ArchivesDoc ->
                    StringUtils.isNotEmpty(ArchivesDoc.getStoragePeriod()) && ArchivesDoc.getStoragePeriod().equals(dic.getDicCode()) && ArchivesDoc.getFileType().equals(DicDocFileType.DOC.getKey())
                            && ArchivesDoc.getDossierId() == 0
            ).count();

            long count = list.stream().filter(ArchivesDoc -> StringUtils.isNotEmpty(ArchivesDoc.getStoragePeriod()) && ArchivesDoc.getStoragePeriod().equals(dic.getDicCode())).count();
            Map countInfo = new HashMap();
            countInfo.put("dossierNum", dossierNum);
            countInfo.put("docNum", docNum);
            countInfo.put("totalNum", dossierNum + docNum);
            storagePeriodMap.put(dic.getDicValue(), countInfo);
        }

        dto.setStoragePeriodMap(storagePeriodMap);


        //==========档案来源统计
        Map fromMap = new HashMap();

        Map fMap = new HashMap();
        int fromDossier1 = archivesService.statisticsArchivesFrom(DicDocFrom.FROM_1,DicDocFileType.DOSSIER,fondsId,typeId);
        int fromDoc1 = archivesService.statisticsArchivesFrom(DicDocFrom.FROM_1,DicDocFileType.DOC,fondsId,typeId);

        Map<String, Object> filesParamFromDoc1 = new HashMap();
        filesParamFromDoc1.put("docFrom", DicDocFrom.FROM_1.getKey());
        filesParamFromDoc1.put("fileType", DicDocFileType.DOC.getKey());
        filesParamFromDoc1.put("state", DicDocState.archive.getKey());
        filesParamFromDoc1.put("isDelete", BaseConstants.DELETE_NORMAL);
        filesParamFromDoc1.put("fondsId",fondsId);
        filesParamFromDoc1.put("typeId",typeId);
        String fileNum1 = archivesService.gainDocFileList(filesParamFromDoc1);

        fMap.put("totalNum",fromDossier1+fromDoc1);
        fMap.put("totalFileSize",fileNum1);
        fromMap.put(DicDocFrom.FROM_1.getValue(),fMap);

        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
            fMap = new HashMap();
            int fromDossier2 = archivesService.statisticsArchivesFrom(DicDocFrom.FROM_2,DicDocFileType.DOSSIER,fondsId,typeId);
            int fromDoc2 = archivesService.statisticsArchivesFrom(DicDocFrom.FROM_2,DicDocFileType.DOC,fondsId,typeId);

            Map<String, Object> filesParamFromDoc2 = new HashMap();
            filesParamFromDoc2.put("docFrom", DicDocFrom.FROM_2.getKey());
            filesParamFromDoc2.put("fileType", DicDocFileType.DOC.getKey());
            filesParamFromDoc2.put("state", DicDocState.archive.getKey());
            filesParamFromDoc2.put("isDelete", BaseConstants.DELETE_NORMAL);
            filesParamFromDoc2.put("fondsId",fondsId);
            filesParamFromDoc2.put("typeId",typeId);
            String fileNum2 = archivesService.gainDocFileList(filesParamFromDoc2);

            fMap.put("totalNum",fromDossier2+fromDoc2);
            fMap.put("totalFileSize",fileNum2);
            fromMap.put(DicDocFrom.FROM_2.getValue(),fMap);
        }


        fMap = new HashMap();
        int fromDossier3 = archivesService.statisticsArchivesFrom(DicDocFrom.FROM_3,DicDocFileType.DOSSIER,fondsId,typeId);
        int fromDoc3 = archivesService.statisticsArchivesFrom(DicDocFrom.FROM_3,DicDocFileType.DOC,fondsId,typeId);

        Map<String, Object> filesParamFromDoc3 = new HashMap();
        filesParamFromDoc3.put("docFrom", DicDocFrom.FROM_3.getKey());
        filesParamFromDoc3.put("fileType", DicDocFileType.DOC.getKey());
        filesParamFromDoc3.put("state", DicDocState.archive.getKey());
        filesParamFromDoc3.put("isDelete", BaseConstants.DELETE_NORMAL);
        filesParamFromDoc3.put("fondsId",fondsId);
        filesParamFromDoc3.put("typeId",typeId);
        String fileNum3 = archivesService.gainDocFileList(filesParamFromDoc3);

        fMap.put("totalNum",fromDossier3+fromDoc3);
        fMap.put("totalFileSize",fileNum3);
        fromMap.put(DicDocFrom.FROM_3.getValue(),fMap);

        dto.setFromMap(fromMap);



//        //=========控制卷数
//        QueryWrapper<ArchivesDoc> queryWrapperDoc5 = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc5.eq("fileType", "dossier");
//        queryWrapperDoc5.eq("openState", "2");
//        queryWrapperDoc5.in("state", new String[]{"2", "3"});
//        Integer ojuanCount = archivesDocMapper.selectCount(queryWrapperDoc5);
//        map.put("ojuanCount", ojuanCount != null ? ojuanCount : 0);
//
//
//        //=========控制件数
//        QueryWrapper<ArchivesDoc> queryWrapperDoc6 = new QueryWrapper<ArchivesDoc>();
//        queryWrapperDoc6.eq("fileType", "doc");
//        queryWrapperDoc6.eq("openState", "2");
//        queryWrapperDoc6.eq("isDelete", "0");
//        queryWrapperDoc6.in("state", new String[]{"2", "3"});
//        Integer ojianCount = archivesDocMapper.selectCount(queryWrapperDoc6);
//        map.put("ojianCount", ojianCount != null ? ojianCount : 0);
        return ResultUtil.success(dto);


    }


}
